<!-- 用户管理 -->
<template>
  <div class="children_content">
    <div class="children_content_flex">
      <role-content ref="roleContentRef" @selected="treeSelected" />

      <div class="right_box">
        <div v-if="roleName" class="add_btns_box">
          <div class="box_left">
            <div class="title">{{roleName}}</div>
          </div>
          <div class="box_right">
            <Space>
              <Button type="primary" @click="userEdit()">添加用户到角色</Button>
              <Button type="primary" @click="editRole">修改角色</Button>
              <Button type="error" @click="delRole">删除角色</Button>
              <Button type="primary" @click="roleAuthorizeDialogDisplay = true">角色授权</Button>
            </Space>
          </div>
        </div>
        <searchGroup v-model="searchObj" :options="searchOptions" @search="searchChange"
          @getHeight="setHeight" />

        <div class="content_table">
          <TemplateTable ref="tableRef" :data="tableData" :columns="tableColumns" :loading="loading"
            :height="tableHeight" :page="pageIndex" :page-size="pageSize" :total="total"
            border="none" size="small" stripe @page-change="handlePageChange" />
        </div>
      </div>
    </div>
  </div>

  <edit-dialog ref="userEditRef" v-if="showAdd" @cancel="showAdd = false" @submit="editSuccess" />
  <role-authorize-dialog v-if="roleAuthorizeDialogDisplay" :roleId="roleId"
    @cancel="roleAuthorizeDialogDisplay = false" />
</template>
<script setup>
import { ref, onMounted, getCurrentInstance, inject, watch, nextTick, computed } from 'vue'
import { Message } from 'view-ui-plus'

import { roleList, roleDelete, roleRemoverole } from '@/api/modules/role'

import EditDialog from './components/EditDialog.vue'
import RoleContent from './components/RoleContent/index.vue'
import RoleAuthorizeDialog from './components/RoleAuthorizeDialog.vue'

// 屏幕高度
const screenHeight = inject('screenHeight')
// 搜索组件高度
const searchHeight = ref(null)
// 表格高度
const tableHeight = ref(0)
// 监听 screenHeight 的变化
watch(
  screenHeight,
  newHeight => {
    if (searchHeight.value) {
      tableHeight.value = newHeight - searchHeight.value - 245
    }
  },
  { immediate: true }
)

// 是否显示新增
const showAdd = ref(false)

// 当前对象
const { proxy } = getCurrentInstance()

// 搜索条件字段
const searchObj = ref({
  username: '',
  id: '',
  mobile: '',
  email: ''
})

// 搜索条件配置
const searchOptions = ref([
  { type: 'input', model: 'username', placeholder: '请输入关键字', label: '用户名称:' },
  //   { type: 'input', model: 'id', placeholder: '请输入关键字', label: '用户ID:' },
  // { type: 'select', model: 'departmentId', placeholder: '请选择部门', label: '所属部门:', dataList: departmentList.value },
  { type: 'input', model: 'mobile', placeholder: '请输入关键字', label: '电话:' },
  { type: 'input', model: 'email', placeholder: '请输入关键字', label: '邮箱:' }
  // { type: 'daterange', model: 'date', placeholder: '请选择日期', label: '创建日期:' },
])

const pageIndex = ref(1)
const pageSize = 20
const total = ref(0)
// 表单元素对象
const tableRef = ref(null)
const roleContentRef = ref(null)
// 列表数据
const tableData = ref([])

// 加载状态
const loading = ref(false)
const roleAuthorizeDialogDisplay = ref(false)

// 表格列配置
const tableColumns = computed(() => [
  {
    title: '用户',
    minWidth: 200,
    formatter: ({ row }) => {
      return row.user.username
    }
  },
  {
    title: '姓名',
    minWidth: 200,
    formatter: ({ row }) => {
      return row.user.uname
    }
  },
  {
    title: '电子邮件',
    minWidth: 200,
    formatter: ({ row }) => {
      return row.user.email
    }
  },
  {
    title: '手机',
    minWidth: 200,
    formatter: ({ row }) => {
      return row.user.mobile
    }
  },
  {
    title: '操作',
    type: 'action',
    width: 80,
    align: 'center',
    fixed: 'right',
    actions: [
      {
        text: '移除',
        type: 'del',
        onClick: row => handleRemoveUser(row)
      }
    ]
  }
])

let roleId
const roleName = ref('')
const treeSelected = data => {
  roleName.value = data.name
  if (roleId === data.id) return
  roleId = data.id
  getRoleList(true)
}

const delRole = () => {
  proxy.$Modal.confirm({
    mask: false,
    title: '警告',
    content: '<p>是否删除该数据?!</p>',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      await roleDelete({
        data: {
          id: roleId
        }
      })

      Message.success('确认删除')
      roleContentRef.value.getRoleList(true)
    }
  })
}

// 获取组件高度
const setHeight = height => {
  searchHeight.value = height
  tableHeight.value = screenHeight.value - searchHeight.value - 245
}

// 获取角色列表
const getRoleList = reset => {
  if (reset) {
    pageIndex.value = 1
  }

  loading.value = true

  roleList({
    query: {
      p: pageIndex.value,
      ps: pageSize
    },
    data: {
      ...searchObj.value,
      id: roleId
    }
  })
    .then(({ list }) => {
      tableData.value = list?.content || []
      total.value = list?.totalElements || 0
    })
    .finally(() => {
      loading.value = false
    })
}

// 处理页码变化
const handlePageChange = page => {
  pageIndex.value = page
  getRoleList()
}

// 处理移除用户
const handleRemoveUser = row => {
  proxy.$Modal.confirm({
    mask: false,
    title: '警告',
    content: '<p>是否移除该用户?</p>',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        await roleRemoverole({
          data: {
            ids: [row.user.id],
            id: roleId
          }
        })

        Message.success('移除成功')
        getRoleList()
      } catch (error) {
        console.error(error)
        Message.error('移除失败')
      }
    }
  })
}

const searchChange = () => {
  getRoleList(true)
}

const userEditRef = ref(null)
const userEdit = () => {
  showAdd.value = true
  nextTick(() => {
    userEditRef.value.initDialog(roleId)
  })
}

const editRole = () => {
  roleContentRef.value.editRole(true)
}

const editSuccess = () => {
  showAdd.value = false

  getRoleList()
}

onMounted(() => {})
</script>

<style lang="scss" scoped></style>